package com.wyq.jpa.service;

import java.util.List;
import java.util.Random;

import com.wyq.jpa.model.Blog;
import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.wyq.jpa.dao.LinkDao;
import com.wyq.jpa.model.Link;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;

@Service
public class LinkService {

	Logger logger = LoggerFactory.getLogger(this.getClass());

	@PersistenceContext(unitName = "acme")
	EntityManager em;

	@Autowired
	JpaTransactionManager transactionManager;

	@Autowired
	BasicDataSource dataSource;

	@Autowired
	LinkDao linkdao;
	public List<Link> getLinks(){
		return linkdao.findAll();
	}

	@Transactional
	public void update() {
		Link link = linkdao.findOne("0005747C-86B4-4DB8-9541-0A27B783FF14");
		link.setName(new Random().nextInt(1000) + "");
		linkdao.save(link);

		Link link1 = linkdao.findOne("0005747C-86B4-4DB8-9541-0A27B783FF14");
		logger.debug(link1.toString());

		Link link2 = em.find(Link.class, "0005747C-86B4-4DB8-9541-0A27B783FF14");
		logger.debug(link2.toString());
	}

	@Transactional
	public void insert() {
		logger.info("最大链接数-->" + dataSource.getMaxActive());
		logger.info("当前活动链接-->" + dataSource.getNumActive());
		logger.info("当前空闲链接-->" + dataSource.getNumIdle());
		Link link = new Link();
		Blog b = new Blog();
		b.setId(1);
		link.setBlog(b);
		link.setName("阿里");
		link.setUrl("http://www.alipay.com");
		linkdao.save(link);
	}

	
}
